package com.autonavi.yunda.yunji.controller.validator;

import com.autonavi.yunda.yunji.common.exception.AmapException;
import com.autonavi.yunda.yunji.controller.validator.annotation.EngineDateValid;
import com.autonavi.yunda.yunji.core.enums.ParamType;
import com.autonavi.yunda.yunji.core.vo.EngineData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author sunzhenbang
 */
@Slf4j
public class EngineDateValidator implements ConstraintValidator<EngineDateValid, String> {

    @Override
    public void initialize(EngineDateValid constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
    }

    @Override
    public boolean isValid(String engineDataStr, ConstraintValidatorContext context) {
        context.disableDefaultConstraintViolation();
        try {
            if (StringUtils.isBlank(engineDataStr)) {
                return true;
            }
            engineDataStr = new String(Base64.getDecoder().decode(engineDataStr.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8);
            EngineData engineData = new EngineData(engineDataStr);
            engineData.fetchStartNode().inputParams.forEach(param -> ParamType.fromCode(param.getType()));
            engineData.nodes.forEach(baseNode -> baseNode.params.forEach(param -> ParamType.fromCode(param.getType())));
            return true;
        } catch (AmapException e) {
            log.info("engineData 转换失败", e);
            context.buildConstraintViolationWithTemplate("engineData 转换失败" + e.getErrorMessage()).addConstraintViolation();
        } catch (Exception e) {
            log.info("engineData 转换失败", e);
            context.buildConstraintViolationWithTemplate("engineData 转换失败" + e.getMessage()).addConstraintViolation();
        }
        return false;
    }
}
